package main

import (
	"flag"
	"fmt"
	"gitee.com/xiaochengtech/unified-structure/src/common"
	_ "gitee.com/xiaochengtech/unified-structure/src/plugin/go"
	_ "gitee.com/xiaochengtech/unified-structure/src/plugin/ts"
	"gitee.com/xiaochengtech/unified-structure/src/util"
	"io/ioutil"
	"log"
	"path/filepath"
	"strings"
)

var srcFlag = flag.String("src", "", "源目录地址")
var destFlag = flag.String("dest", "", "目标目录地址")
var languageFlag = flag.String("language", "", "导出语言")

func main() {
	flag.Parse()
	// 获取处理插件
	handle := common.GetPlugin(*languageFlag)
	// 验证源目录和目标目录
	srcFiles, err := ioutil.ReadDir(*srcFlag)
	if err != nil {
		helpInfo()
		log.Fatalln("\n无法读取源目录")
	}
	_, err = ioutil.ReadDir(*destFlag)
	if err != nil {
		helpInfo()
		log.Fatalln("\n无法读取目标目录")
	}
	// 生成Context
	ctx := common.Context{}
	// 读取目录中的index.json
	util.ReadJsonFile(filepath.Join(*srcFlag, "index.json"), &ctx.Dir)
	// 遍历文件
	for _, srcFile := range srcFiles {
		fileName := srcFile.Name()
		srcFilePath := filepath.Join(*srcFlag, fileName)
		// 忽略目录
		if srcFile.IsDir() {
			log.Println("忽略目录", fileName)
			continue
		}
		// 选择性拷贝非Json文件
		if !strings.Contains(fileName, ".json") {
			if handle.CanCopy(ctx, fileName) {
				data := util.ReadFile(srcFilePath)
				util.WriteFile(filepath.Join(*destFlag, fileName), data)
			}
			continue
		}
		// 拆分文件名
		fileNameParts := strings.Split(fileName, ".")
		ctx.CurFileName = fileNameParts[0]
		// 读取文件
		var fileObj common.File
		util.ReadJsonFile(srcFilePath, &fileObj)
		ctx.File = fileObj
		// 处理
		hasLanguage := false
		for _, language := range ctx.File.Language {
			hasLanguage = hasLanguage || language == *languageFlag
		}
		if !hasLanguage {
			continue
		}
		// 处理普通文件
		filename, content := handle.GetMainFile(ctx)
		if len(filename) > 0 {
			destFilePath := filepath.Join(*destFlag, filename)
			util.WriteFile(destFilePath, []byte(content))
		}
		log.Println("处理完成" + fileName)
	}
	// 处理index文件
	for {
		filename, content := handle.GetOtherFile(ctx)
		if len(filename) > 0 {
			destFilePath := filepath.Join(*destFlag, filename)
			util.WriteFile(destFilePath, []byte(content))
		} else {
			break
		}
	}
	return
}

func helpInfo() {
	fmt.Println("go run src/main.go [OPTIONS]")
	fmt.Println("")
	fmt.Println("OPTIONS:")
	flag.PrintDefaults()
}
